<template>
    <div v-if="receivedProps.historyFileList" class="uploadHis">
        <ul class="file-list">
            <li v-for="file in receivedProps.historyFileList" :key="file.objectId">
                <span>{{ file.fileName }}</span>
                <el-icon>
                    <Download @click="fileOpeartion.downloadFile(file.objectId, file.fileName)" />
                </el-icon>
                <el-icon>
                    <Delete @click="deleteFile(file.objectId)" />
                </el-icon>
            </li>
        </ul>
    </div>
    <div class="upload">
        <el-upload class=" upload-button" ref="uploadRef" :file-list="uploadFileList" multiple
            :action="ApiConfig.PATH.File.Upload" :headers="headers" method="post"
            :data="{ key: commonUtil.Methods.generateGUID() }" :auto-upload="false" :on-preview="handlePreview"
            :on-remove="handleRemove" :on-change="handleChange" :on-progress="handleProgress"
            :before-upload="beforeUpload" :on-success="handleSuccess" :on-error="handleError">
            <template #trigger>
                <el-button type="info" plain>选择附件</el-button>
            </template>
            <el-button type="primary" plain @click="submitUploadFile">
                上传
            </el-button>
        </el-upload>
    </div>
</template>

<script lang="ts" setup>
import { ref, inject, defineProps, defineEmits } from 'vue';
import type { UploadInstance, UploadUserFile, UploadFile } from 'element-plus';
import { useLoginUserStore } from '../../store';
import { useUploadFileStore } from '../../store/useUploadFileStore';
import commonUtil from "../../utils/common";
import { useFileOperation } from '../../hooks/Common/useFileOperation';

let receivedProps = defineProps(["historyFileList"]);
let emit = defineEmits(['file-delete']); // 定义文件删除事件

let ApiConfig = inject("ApiConfig") as any;

let uploadRef = ref<UploadInstance>()
let uploadFileList = ref<UploadUserFile[]>([]);
let loginUserStore = useLoginUserStore();
let uploadFileStore = useUploadFileStore();
uploadFileStore.init();//附件初始化

let fileOpeartion = useFileOperation();

let headers = ref({
    Authorization: `Bearer ${loginUserStore.token}`,
});

function submitUploadFile() {
    // console.log("submitUploadFile  fileList.value", uploadFileList.value)
    if (uploadFileList.value) {
        // Ensure there are files to upload
        if (uploadFileList.value.length > 0) {
            uploadRef.value!.submit();
        } else {
            console.warn('No files to upload');
        }
    } else {
        console.error('Upload instance is not initialized');
    }
}

function handlePreview(uploadFile: UploadFile) {
    console.log("handlePreview", uploadFile)
}
function handleRemove(uploadFile: UploadFile) {
    console.log("handleRemove", uploadFile)
}
function handleProgress(event: ProgressEvent, file: UploadUserFile, fileList: UploadUserFile[]) {
    // 更新文件的上传进度
    const updatedFile = fileList.find(f => f.uid === file.uid);
    // console.log("updatedFile",updatedFile)
    if (updatedFile) {
        updatedFile.percentage = Math.round((event.loaded / event.total) * 100); // 计算百分比
    }
    uploadFileList.value = fileList;
}
function handleChange(file: UploadUserFile, fileList: UploadUserFile[]) {
    //检查是否有未上传的附件
    let notUploadFile = fileList.find(f => f.status != "success");

    if (notUploadFile) {
        uploadFileStore.hasNotUploadFile = true;
    }
    else {
        uploadFileStore.hasNotUploadFile = false;
    }

    uploadFileList.value = fileList;
}
function beforeUpload() {
    // 你可以在这里检查文件类型、大小等
    // console.log("beforeUpload", rawFile)
    return true; // 返回 true 允许文件上传
}
function handleSuccess(response: any) {
    let upl = response.data;
    upl.forEach(uploadedFile => {
        let file = uploadFileList.value.find(f => f.name === uploadedFile.fileName);
        if (file) {
            file.status = 'success';
            uploadFileStore.uploadedFileList.push({ name: file.name, objectId: uploadedFile.objectId });
        }
    });
}
function handleError(error: any) {
    uploadFileStore.hasNotUploadFile = true;
    console.error('Upload error:', error);
}

// 删除文件的处理函数
async function deleteFile(objectId) {
    fileOpeartion.deleteFile(objectId).then((result) => {
        if (result) {
            // 文件删除成功，触发事件通知父组件
            emit('file-delete', objectId);
        }
    })
}
</script>